package cn.appsys.controller.deve;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.mysql.jdbc.StringUtils;

import cn.appsys.constant.Constants;
import cn.appsys.pojo.AppCategory;
import cn.appsys.pojo.AppInfo;
import cn.appsys.pojo.AppVersion;
import cn.appsys.pojo.DataDictionary;
import cn.appsys.pojo.DevUser;
import cn.appsys.pojo.Page;
import cn.appsys.service.deve.appcategory.DeveAppCategoryService;
import cn.appsys.service.deve.appinfo.DeveAppInfoService;
import cn.appsys.service.deve.appversion.DeveAppVersionService;
import cn.appsys.service.deve.datadictionary.DeveDataDictionaryService;

@Controller
@RequestMapping("/deve/appinfo")
public class DeveAppController {

	@Resource
	private DeveAppInfoService devAppInfoService;

	@Resource
	private DeveDataDictionaryService deveDataDictionaryService;

	@Resource
	private DeveAppCategoryService deveAppCategoryService;

	@Resource
	private DeveAppVersionService deveAppVersionService;
	
	
	/*//上架,下架
	@RequestMapping(value ="/sale", method = RequestMethod.POST)
	@ResponseBody
	public Object sale(@PathVariable("addId")String addId,HttpSession session){
		Map<String, String> resultMap=new HashMap<String, String>();
		Integer appIdInt=0;
		try {
			appIdInt=Integer.parseInt(addId);
		} catch (Exception e) {
			appIdInt=0;
		}
		resultMap.put("errorCode","0" );
		if(appIdInt>0){
			try {
				DevUser devUser=(DevUser)session.getAttribute(Constants.DEV_USER_SESSION);
				AppInfo appInfo=new AppInfo();
				appInfo.setId(appIdInt);
				appInfo.setModifyBy(devUser.getId());
				if(devAppInfoService.appsysUpdeteByAppId(addId)){
					resultMap.put("resultMap", "success");
				}else{
					resultMap.put("resultMap", "failed");
				}
			} catch (Exception e) {
				resultMap.put("errorCode", "exception000001");
			}
		}else{
			resultMap.put("errorCode", "param000001");
		}
		return resultMap;
	}*/
	
	
	//删除App版本
	@RequestMapping(value="/delapp")
	@ResponseBody
	public Object delapp(@RequestParam String id){
		Map<String, String> resultMap=new HashMap<String, String>();
		if(StringUtils.isNullOrEmpty(id)){
			resultMap.put("delResult", "notexist");
		}else{
			try {
				if(devAppInfoService.deleteAppInfoById(Integer.parseInt(id))){
					resultMap.put("delResult", "true");
				}else{
					resultMap.put("delResult", "false");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return resultMap;
	}
	
	//查看APP信息
	@RequestMapping("/appview/{id}")
	public String appview(@PathVariable("id")Integer appId,Model model){
		//1.通过app的主键id查询app的详细信息
		AppInfo appInfo=devAppInfoService.queryById(appId);
		//2.通过app的主键id将当前app的历史版本列表信息查询出来
		List<AppVersion> appVersionList=deveAppVersionService.getAppVersionByAppId(appId);
		//3.将app的详细信息和当前app的历史版本列表信息保存到Model对象
		model.addAttribute("appInfo",appInfo);
		model.addAttribute("appVersionList",appVersionList);
		//4.跳转到appinfoview.jsp app的详细页面
		return "developer/appinfoview";
		
	}
	// 跳转到app版本修改页面。
	@RequestMapping(value = "/appinfomodifysava", method = RequestMethod.POST)
	public String appinfomodifysava(AppInfo appInfo,
			@RequestParam("attach") MultipartFile attach, Model model,
			HttpServletRequest request, HttpSession session) {

		String logoLocPath = ""; // 上传图片的绝对路径
		String logoPicPath = ""; // 上传图片的相对路径
		if (!attach.isEmpty()) {
			// 获取文件上传所需要的路径
			String path = request.getSession().getServletContext()
					.getRealPath("statics" + File.separator + "uploadfiles");
			String oldFileName = attach.getOriginalFilename(); // 得到原文件名
			String suffix = FilenameUtils.getExtension(oldFileName); // 原文件的后缀
			if (attach.getSize() > 5000000) {
				model.addAttribute("fileUploadError", "* 上传文件的大小超过500KB，上传失败！");
			} else if (suffix.equalsIgnoreCase("jpg")
					|| suffix.equalsIgnoreCase("png")
					|| suffix.equalsIgnoreCase("jepg")
					|| suffix.equalsIgnoreCase("pneg")) {// 上传图片格式
				String fileName = appInfo.getAPKName() + ".jpg";// 上传LOGO图片命名:apk名称.apk
				File file = new File(path, fileName);
				if (!file.exists()) {
					file.mkdirs();
				}
				try {
					attach.transferTo(file);
				} catch (IllegalStateException | IOException e) {
					model.addAttribute("fileUploadError", "* 文件上传失败");
					e.printStackTrace();
				}
				logoPicPath = request.getContextPath()
						+ "/statics/uploadfiles/" + fileName;
				logoLocPath = path + File.separator + fileName;
			}
		}

		// 获取当前登录的用户对象
		DevUser user = (DevUser) session
				.getAttribute(Constants.DEV_USER_SESSION);
		appInfo.setModifyBy(user.getId());
		appInfo.setModifyDate(new Date());
		appInfo.setLogoPicPath(logoPicPath);
		appInfo.setLogoLocPath(logoLocPath);
		int result = devAppInfoService.updateAppInfo(appInfo);
		if (result > 0) {
			return "redirect:/deve/appinfo/list";
		} else {
			//修改失败的话，就去访问appinfomodify方法，通过id查询app信息后跳转到修改页面并显示app信息，继续进行修改操作
			return "redirct:/deve/appinfo/appinfomodify/" + appInfo.getId();
		}
	}

	// 从appinfomodify.js中发送过来的ajax请求实现的效果是:1.将上传到tomcat服务器中的图片给删除。
	// 2、将app信息的表app_info中 的logoPicPath和logoLocPath两个列的值给清空
	@RequestMapping("/delfile")
	@ResponseBody
	public Object delfile(@RequestParam("id")Integer id) {
		Map<String, String> map = new HashMap<String, String>();
		if (id == null || id == 0) {
			map.put("result", "empty");
		} else {
			AppInfo appInfo = devAppInfoService.queryById(id); // 通过id查询app详情信息
			File file = new File(appInfo.getLogoLocPath()); // 通过app的1ogo图片的绝对路径创建File对象
			if (file.exists()) {
				// 表示tomcat服务器上存在之前上传的图片文件,I这里将服务器上的图片文件删除
				if (file.delete()) { // 调用delete ()方法将服务器上的图片文件删除true表示删除成功，
					// 在将服务上的图片删除后，还要将app_ info中的logoPicPath和logoLocPath两个列的值给清空
					if (devAppInfoService.updateEmptyLogPath(id) > 0) {
						map.put("result", "success");
					} else {
						map.put("result", "failed");
					}
				} else {
					map.put("result", "failed");
				}
			} else {
				map.put("result", "fileNoExist"); // 标识要删除的文件不存在
			}
		}
		return map;
	}

	// 通过parentId的值查询app_ category表中的分类列表信 息
	@RequestMapping(value = "/getCategoryByParentId", method = RequestMethod.GET)
	@ResponseBody
	public Object getCategoryByParentId(@RequestParam("pid") Integer pid) {
		// 1.调用service,实现通过parentId查询分类列表信息/
		List<AppCategory> categoryList = deveAppCategoryService.queyById(pid);
		// 2、返回查询出来的分类列表信息，会自动转换成JSON字符串，并输出浏览器客户端中
		return categoryList;
	}

	@RequestMapping(value = "/getPlatformByTypeCode", method = RequestMethod.GET)
	@ResponseBody
	// 将当前方法的返回值在转换成JSON字符串输出浏览器客户端，即ajax的成功回调函数中
	public Object getPlatformByTypeCode(@RequestParam("tcode") String tcode) {
		// 1.通过typeCode去数据字典表中将所属平台列表查询出来。
		List<DataDictionary> platfromList = deveDataDictionaryService.findCategoryByTypeCode(tcode);
		// 2.查询出来后，直接进行返回，会自动转换成JSON字符串。
		return platfromList;

	}

	/**
	 * 实现通过id查询app详细对象信息,然后再跳转到app修改页面并显示当前app信息
	 * 
	 * @param id
	 *            从appinfolist.js中[修改]链接点击事件中传递过来的app信息id
	 * @return
	 */
	@RequestMapping(value = "/appinfomodify/{id}")
	public String appinfomodify(@PathVariable("id") Integer id, Model model) {
		// 1. 调用service,实现通过id查询app详细对象信息
		AppInfo appInfo = devAppInfoService.queryById(id);
		// 2、将诮细信息保存到Mode1对象中，
		model.addAttribute("appInfo", appInfo);
		// 3.跳转到appinfomodify.jsp页面中,并显示app信息
		return "developer/appinfomodify";

	}

	// 保存新增的app信息
	@RequestMapping(value = "/appinfoaddsave", method = RequestMethod.POST)
	public String appinfoaddsave(AppInfo appInfo, Model model,
			HttpServletRequest request,
			@RequestParam("a_logoPicPath") MultipartFile attach,
			HttpSession session) {
		String logoPicPath = ""; // 用于保存图片相对路径格式如:1
		String logoLocPath = ""; // 用于保存图片的绝对路径

		// 实现图片上传
		if (!attach.isEmpty()) {
			String path = session.getServletContext().getRealPath(
					"statics" + File.separator + "uploadfiles"); // 获取文件上传所需要的路径。
			String oldFileName = attach.getOriginalFilename(); // 得到上传图片的原文件名
			String suffix = FilenameUtils.getExtension(oldFileName); // 得到原文件的后缀
			if (attach.getSize() > 5000000) { // 如果上传文件的大小超过500kb
				model.addAttribute("fileUploadError", "* 上传文件的大小超过500kb，上传失败！");
			} else if (suffix.equalsIgnoreCase("jpg")
					|| suffix.equalsIgnoreCase("png")
					|| suffix.equalsIgnoreCase("jpeg")
					|| suffix.equalsIgnoreCase("pneg")) {
				// 判断用户上传的文件格式是否是jpg、png、jpeg、pneg格式
				String fileName = appInfo.getAPKName() + ".jpg";// 获取上传之后的文件名字，因为
																// APKName是唯一
				File file = new File(path, fileName); // 根据文件对象
				if (!file.exists()) { // 如果文件对象不存在，那么就创建这个目录
					file.mkdirs(); // 创建这个目录
				}
				try {
					attach.transferTo(file);// 将attach上传到指定的目录中去
				} catch (IllegalStateException | IOException e) {
					model.addAttribute("fileUploadError", "* 文件上传失败");
					e.printStackTrace();
				}
				logoPicPath = request.getContextPath()
						+ "/statics/uploadfiles/" + fileName; // 用于保存图片相对路径格式如：/AppInfoSystem/statics/uploadfiles/com.lbe.security.jpg
				logoLocPath = path + File.separator + fileName; // 保存的是图片的绝对路径
			}
		}
		appInfo.setLogoPicPath(logoPicPath); // 相对路径
		appInfo.setLogoLocPath(logoLocPath); // 绝对路径
		// 获取当前登录用户
		DevUser user = (DevUser) session
				.getAttribute(Constants.DEV_USER_SESSION);
		appInfo.setCreatedBy(user.getId());
		appInfo.setCreationDate(new Date());
		int result = devAppInfoService.addSave(appInfo);
		if (result > 0) {
			return "redirect:/deve/appinfo/list";
		} else {
			return "developer/appinfoadd"; // 失败再跳回新增页面
		}
	}

	@RequestMapping(value = "/apkNameIsExist", method = RequestMethod.GET)
	@ResponseBody
	public Object apkNameIsExist(@RequestParam("APKName") String apkName) {
		Map<String, String> map = new HashMap<String, String>();
		if (StringUtils.isNullOrEmpty(apkName)) {
			map.put("APKName", "empty");
		} else {
			// 通过从页面上传递过来的apk名称查询app信息
			AppInfo appInfo = devAppInfoService.querAppByApkName(apkName);
			if (appInfo != null) {
				map.put("APKName", "exist");
			} else {
				map.put("APKName", "noexist");
			}
		}

		return map;
	}

	@RequestMapping(value = "/getDataDictionaryByTypeCode")
	@ResponseBody
	public Object getDataDictionaryByTypeCode(
			@RequestParam("tcode") String tCode) {
		// 通过typeCode查询app_category信息
		List<DataDictionary> dataList = deveDataDictionaryService
				.findCategoryByTypeCode(tCode);
		return dataList;
	}

	// 跳转到新增App页面--appinfoadd.jsp
	@RequestMapping(value = "/appinfoadd")
	public String appinfoadd() {
		return "developer/appinfoadd";
	}

	// 根据一级分类的Id,查询其子类分类列表信息
	@RequestMapping("/queryCategoryListByParentId/{parentId}")
	@ResponseBody
	public Object queryCategoryListByParentId(
			@PathVariable("parentId") Integer parentId) {
		parentId = parentId == 0 ? null : parentId;
		List<AppCategory> appCategory = deveAppCategoryService
				.queyById(parentId);
		return appCategory;
	}

	// 用于按条件查询并分页显示App信息列表
	@RequestMapping("/list")
	public String list(
			@RequestParam(value = "querySoftwareName", required = false) String querySoftwareName,
			@RequestParam(value = "queryStatus", required = false) Integer queryStatus,
			@RequestParam(value = "queryFlatformId", required = false) Integer queryFlatformId,
			@RequestParam(value = "queryCategoryLevel1", required = false, defaultValue = "0") Integer queryCategoryLevel1,
			@RequestParam(value = "queryCategoryLevel2", required = false, defaultValue = "0") Integer queryCategoryLevel2,
			@RequestParam(value = "queryCategoryLevel3", required = false, defaultValue = "0") Integer queryCategoryLevel3,
			@RequestParam(value = "currPageNo", required = false, defaultValue = "1") Integer currPageNo,
			Model model) {

		// 1.获取记录数
		int totalCount = devAppInfoService.getTotalCount(querySoftwareName,
				queryStatus, queryFlatformId, queryCategoryLevel1,
				queryCategoryLevel2, queryCategoryLevel3);
		// 2.封装Page对象
		Page page = new Page();
		page.setPagesize(5);
		page.setCurrPageNo(currPageNo);
		page.setTotalCount(totalCount);
		// 创建from,分页所需要的起始位置偏移量
		Integer from = (page.getCurrPageNo() - 1) * page.getPagesize();
		// 3、调用service分页查询APP信息列表
		List<AppInfo> appInfoList = devAppInfoService.findAppInfoPage(
				querySoftwareName, queryStatus, queryFlatformId,
				queryCategoryLevel1, queryCategoryLevel2, queryCategoryLevel3,
				from, page.getPagesize());

		// 4、 查询appinfolist. jsp页面中APP状态下拉框中的数据准备好 key为statusList
		List<DataDictionary> statusList = deveDataDictionaryService
				.findCategoryByTypeCode("APP_STATUS");
		// 5.查询appinfolist.jsp页面中所属平台下拉框中的数据准备好，key为flatFormList
		List<DataDictionary> flatFormList = deveDataDictionaryService
				.findCategoryByTypeCode("APP_FLATFORM");
		// 6.将三级分类信息查询出来
		List<AppCategory> categoryLevel1List = deveAppCategoryService
				.queyById(null); // 一级分类, 值查询出一级分类就可以了,
									// 页面上的下拉框三级联动,是通过appinfolist.js实现的.

		// 7、将相关数据保存到Model对象中，供appinfolist.jsp页面进行使用
		model.addAttribute("categoryLevel1List", categoryLevel1List);
		model.addAttribute("pages", page);
		model.addAttribute("appInfoList", appInfoList);
		model.addAttribute("statusList", statusList);
		model.addAttribute("flatFormList", flatFormList);
		// 再将查询条件也保存model对象中
		model.addAttribute("querySoftwareName", querySoftwareName);
		model.addAttribute("queryStatus", queryStatus);
		model.addAttribute("queryFlatformId", queryFlatformId);
		model.addAttribute("queryCategoryLevel1", queryCategoryLevel1);
		model.addAttribute("queryCategoryLevel2", queryCategoryLevel2);
		model.addAttribute("queryCategoryLevel3", queryCategoryLevel3);
		return "developer/appinfolist"; // 跳转到APP信息列表页面，显示查询出来的分页列表页面
	}
}
